<template>
  <div>
    <!-- 返回按钮 -->
    <el-button type="primary" @click="goBack" style="position: absolute; top: 10px; right: 10px;">返回</el-button>

    <!-- 第一张图的内容 -->
    <el-form :model="couponForm" ref="couponFormRef" label-width="120px" style="margin-top: 50px;">
      <el-form-item label="优惠券名称" required>
        <el-input v-model="couponForm.name" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="面值" required>
        <el-input v-model="couponForm.value" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="优惠券类型" prop="type" required>
        <el-select v-model="couponForm.type" placeholder="请选择...">
          <el-option
              v-for="type in types"
              :key="type.id"
              :label="type.type"
              :value="type.type">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="优惠券状态" prop="type" required>
        <el-select v-model="couponForm.status" placeholder="请选择...">
          <el-option
              v-for="type in statuss"
              :key="type.id"
              :label="type.status"
              :value="type.status">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发放量" required>
        <el-input v-model="couponForm.quantity" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="有效期">
        <el-date-picker
            v-model="couponForm.validity"
            type="daterange"
            start-placeholder="选择开始时间"
            end-placeholder="选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="使用会员" required>
        <el-select v-model="couponForm.uname" placeholder="请选择...">
          <el-option
              v-for="a in unames"
              :key="a.id"
              :label="a.uname"
              :value="a.uname"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属门店" required>
        <el-select v-model="couponForm.mname" placeholder="请选择...">
          <el-option
              v-for="a in stores"
              :key="a.id"
              :label="a.mname"
              :value="a.mname"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="可使用的商品">
        <el-radio-group v-model="couponForm.selectedOption">
          <el-radio name="aa" label="全部菜品">全部菜品</el-radio>
          <el-radio name="aa" label="制定菜品">制定菜品</el-radio>
          <el-radio name="aa" label="制定分类">制定分类</el-radio>
        </el-radio-group>
      </el-form-item>

      <div v-if="couponForm.selectedOption === '全部菜品'">
        <el-table :data="dishes" style="width: 100%">
          <el-table-column prop="categoryId" label="菜品编号" width="180"></el-table-column>
          <el-table-column prop="name" label="菜品名称" width="180"></el-table-column>
          <el-table-column prop="price" label="菜品价格" width="180"></el-table-column>
          <el-table-column prop="image" label="菜品图片" width="180"></el-table-column>
          <el-table-column prop="description" label="菜品评价" width="180"></el-table-column>
        </el-table>
        <el-pagination
            background
            layout="prev, pager, next"
            :total="100"
            :page-size="10"
            style="margin-top: 10px;"
        ></el-pagination>
      </div>

      <div v-else-if="couponForm.selectedOption === '制定菜品'">
        <el-button size="mini" type="text" @click="addDish">添加菜品</el-button>
        <el-table :data="dishes" style="width: 100%">
          <el-table-column prop="categoryId" label="菜品编号" width="180"></el-table-column>
          <el-table-column prop="name" label="菜品名称" width="180"></el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button size="mini" type="text" @click="removeDish(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            background
            layout="prev, pager, next"
            :total="100"
            :page-size="10"
            style="margin-top: 10px;"
        ></el-pagination>
      </div>

      <div v-else-if="couponForm.selectedOption === '制定分类'">
        <el-button size="mini" type="text" @click="addDCategories">添加分类</el-button>
        <el-table :data="categories" style="width: 100%">
          <el-table-column prop="name" label="分类名称" width="180"></el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button size="mini" type="text" @click="removeCategory(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-form-item>
        <el-button type="primary" @click="submitCouponForm">确定</el-button>
        <el-button @click="resetCouponForm">取消</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[2, 3, 4, 5]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"></el-pagination>
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {useRouter, useRoute} from 'vue-router'
import {ElMessage} from 'element-plus'
import axios from "axios"

const router = useRouter()
const route = useRoute()

const couponForm = ref({})
const types = ref([])
const unames = ref([])
const stores = ref([])
const couponFormRef = ref(null)
const dishes = ref([])
const categories = ref([])
const statuss = ref([])

//分页效果======================================================================================
let pageNum = ref(1);
let pageSize = ref(3);
let total = ref(1);
const small = ref(false);
const background = ref(true);
const disabled = ref(false);

const handleSizeChange = (val) => {
  pageSize.value = val;
  getalldishes();
}
const handleCurrentChange = (val) => {
  // 将这个val数字赋值给 pageNum
  pageNum.value = val;
  getalldishes();
}
//分页效果======================================================================================

//获取优惠券类型============================================================================
const getTypes = () => {
  axios.get("/coupons/gettype")
      .then((res) => {
        types.value = res.data
      })
      .catch((error) => {
        console.error('获取优惠券类型失败:', error);
        ElMessage.error('获取优惠券类型失败');
      });
};
//获取优惠券类型============================================================================

//获取优惠券状态============================================================================
const getStatus=()=>{
  axios.get("/coupons/getstatus").then((res) => {
    statuss.value = res.data
  })
}
//获取优惠券状态============================================================================

//获取使用会员门槛============================================================================
const getunames = () => {
  axios.get("/coupons/getunames").then((res) => {
    unames.value = res.data
  })
}
//获取使用会员门槛============================================================================

//获取门店名============================================================================
const getStore = () => {
  axios.get("/coupons/getStore").then((res) => {
    stores.value = res.data
  })
}
//获取门店名============================================================================

//获取优惠券的信息======================================================================
const getcouponForm = () => {
  if (route.params.id) {
    axios.get(`/coupons/getcouponForm/${route.params.id}`).then(res => {
      couponForm.value = res.data
    })
  }
}
//获取优惠券的信息======================================================================

//当点击取消按钮时跳转回优惠券页面=================================================================
const resetCouponForm = () => {
  router.push({name: 'CouponList'})
}
//当点击取消按钮时跳转回优惠券页面=================================================================

const submitCouponForm = () => {
  couponFormRef.value.validate((valid) => {
    if (valid) {
      if (route.params.id === null || route.params.id === undefined) {
        axios.post("/coupons/addcouponForm", couponForm.value).then(res => {
          couponForm.value = res.data.obj
          ElMessage.success("新增成功！！！")

        })
      } else {
        axios.put(`/coupons/updatecouponForm/${route.params.id}`, couponForm.value).then(res => {
          couponForm.value = res.data.obj
        })
      }
    } else {
      ElMessage.error('请填写完整表单')
      return false
    }
  })
  router.push({name: 'CouponList'})
}
//删除单个菜品信息=============================================================
const removeDish = (row) => {
  axios.delete(`/coupons/deletedishes/${row.id}`).then(res => {
    ElMessage.success("删除成功")
    getdishes()
  })
}
//删除单个菜品信息=============================================================

//添加单个菜品信息跳转到添加DishSelector==================================================================
const addDish = () => {
  router.push({name: 'DishSelector'})}
//添加单个菜品信息跳转到添加DishSelector==================================================================

//获取菜品category_id, name信息================================================================================
const getdishes = () => {
  axios.get("/coupons/getdishes")
      .then(res => {
        dishes.value = res.data.obj;
      })
      .catch(err => {
        console.error('获取菜品失败:', err)
        ElMessage.error('获取菜品失败')
      })
}
//获取菜品的category_id, name信息================================================================================

//获取全部的分类信息=================================================================================
const getdishcategoryName = () => {
  axios.get("/coupons/getdishcategoryName")
      .then(res => {
        categories.value = res.data
      })
      .catch(err => {
        console.error('获取分类失败:', err)
        ElMessage.error('获取分类失败')
      })
}
//获取全部的分类信息=================================================================================

//获取所有菜品信息==============================================================================
const getalldishes = () => {
  axios.get(`/coupons/getalldishes/${pageNum.value}/${pageSize.value}`)

      .then(res => {
        console.log(res.data.obj.total)
        dishes.value = res.data.obj.data;
        total.value = res.data.obj.total;
      })
      .catch(err => {
        console.error('获取所有菜品失败:', err)
        ElMessage.error('获取所有菜品失败')
      })
}
//获取所有菜品信息==============================================================================

//删除单个分类信息==========================================================================
const removeCategory = (row) => {
  // 实现删除分类逻辑
  axios.delete(`/coupons/deletecategory/${row.id}`).then(res => {
    ElMessage.success("删除成功")
    getdishcategoryName()
  })
}
//删除单个分类信息==========================================================================

//添加分类数据===============================================================================================
const addDCategories = () => {
  router.push({name: 'CategorySelector'})
}
//添加分类数据===============================================================================================

//返回到上一层====================================================================================================
const goBack = () => {
  router.push({name: 'CouponList'})
}
//返回到上一层====================================================================================================

onMounted(() => {
  getdishes()
  getdishcategoryName()
  getalldishes();
  getTypes();
  getunames();
  getStore();
  getcouponForm();
  getStatus();
})
</script>
<style scoped>
.create-table-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.form-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.el-form-item {
  margin-bottom: 22px;
}

.qr-code-section {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.qr-code-notice {
  font-size: 12px;
  color: #999;
  margin: 5px 0;
}

.qr-code-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 10px;
}

.qr-code-image img {
  width: 150px;
  height: 150px;
  border: 1px solid #eee;
  padding: 5px;
}

.qr-code-text {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.form-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
}

.el-button {
  margin-left: 10px;
}
</style>